<template>
  <a-card title="查看房户信息" style="width: 300px;pointer-events: all;">
    <span style="margin-right: 20px;">楼栋选择:</span>
    <a-select ref="select" v-model:value="selectBuild" style="width: 120px" :options="buildsOption"
      @change="handleChange"></a-select>
  </a-card>
</template>

<script setup>
import { getBuild, getHouse, getOneHouseInfo } from '@/api/api'
import { ref, onMounted } from 'vue'
import * as Cesium from 'cesium'
import SimpleLabel from '@/cesiumTools/popup'
import { useMapData } from '@/store'
import { cartesian3ToDegreesHeight } from '@/cesiumTools/utils'

const mapStore = useMapData()
// 获取viewer
const viewer = mapStore.Viewer
const selectBuild = ref(null)
const buildsOption = ref([])

// 组件挂载的时候，渲染下拉列表数据
onMounted(async () => {
  const info = await getBuild()
  if (info.code === 200) {
    const { data } = info
    buildsOption.value = data.map(item => {
      return {
        value: item.id,
        label: item.name,
        polygon: item.polygon
      }
    })
  }
})
const colors = [
  "#99CCCC",
  "#66FF66",
  "#FF6666",
  "#00CCFF",
  "#00FF33",
  "#CC0000",
  "#CC00CC",
  "#CCFF00",
  "#0000FF",
];
const renderPrimitive = (polygon, minHeight, maxHeight, id) => {
  const { coordinates } = polygon
  const positions = coordinates[0].reduce((a, b) => a.concat(b), [])
  const cartesian = new Cesium.Cartesian3.fromDegreesArray(positions)
  const hierachy = new Cesium.PolygonHierarchy(cartesian)
  // 将上一个功能的实现直接迁移过来
  const geometryInstance = new Cesium.GeometryInstance({
    id: id,
    geometry: new Cesium.PolygonGeometry({
      polygonHierarchy: hierachy,
      height: minHeight,
      extrudedHeight: maxHeight,
    }),
    // 这里务必把颜色写在instance中，因为每一户的颜色都不一样，所以不能用appearance来指定颜色
    attributes: {
      color: Cesium.ColorGeometryInstanceAttribute.fromColor(
        Cesium.Color.fromCssColorString(colors[id % 9]).withAlpha(
            0.3
        )
      ),
    }
  })

  const p = new Cesium.ClassificationPrimitive({
    geometryInstances: geometryInstance,
    classificationType: Cesium.ClassificationType.CESIUM_3D_TILE,
  })
  return viewer.scene.primitives.add(p)
}

const handleChange = async (e) => {
  // 不分页请求接口
  const queryParam = {
    id: e,
    noPage: 1
  }
  const info = await getHouse(queryParam)
  if (info.code === 200) {
    const { data } = info
    console.log(data);
    // 遍历data,渲染每一个住户的primitive
    data.forEach(item => {
      const { minHeight, maxHeight, polygon, id } = item
      renderPrimitive(polygon, minHeight, maxHeight, id)
    })
    // 注册一个屏幕空间事件，点击查询
    registerHandler()
  }
}

let handler
let popup = new SimpleLabel(viewer, {
  offset: [200, -200]
})
let lastPick
const registerHandler = () => {
  handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas)
  handler.setInputAction(async (e) => {
    const pick = viewer.scene.pick(e.position)
    const pickPosition = viewer.scene.pickPosition(e.position)
    const positionLng = cartesian3ToDegreesHeight(pickPosition)
    console.log(positionLng);
    if (pick && pick.id) {
      // 根据id去请求接口，调用popup做查询
      const info = await getOneHouseInfo({ id: pick.id })
      if (info.code === 200) {
        // 从接口获取住户的详细信息，然后调用气泡框展示数据
        const { data } = info

        // 如果存在之前点击的图元，将颜色还原
        if (lastPick && lastPick.id) {
          const lastAttributes = lastPick.primitive.getGeometryInstanceAttributes(lastPick.id)
          lastAttributes.color = Cesium.ColorGeometryInstanceAttribute.toValue(
            Cesium.Color.fromCssColorString(colors[lastPick.id % 9]).withAlpha(0.3)
          )
        }
        // 这里修改的不是appearance中的颜色，而是attributes中的颜色，所以要使用ColorGeometryInstanceAttribute来修改
        const attributes = pick.primitive.getGeometryInstanceAttributes(pick.id)
        attributes.color = Cesium.ColorGeometryInstanceAttribute.toValue(Cesium.Color.YELLOW.withAlpha(0.88));
        lastPick = pick

        popup.removeMarker()
        // 修改气泡框的位置
        popup.changePosition(pickPosition)
        popup.addLabel(data)
      }
    }
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
}
</script>
<style scoped></style>